// Package sse is a chat client based on sse.
package sse

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"sync"

	"new_for_deepseek_rabbitmq/project/tencent/lke/event"

	"github.com/r3labs/sse/v2"
)

// Client 会话客户端
type Client interface {
	// On 注册事件监听器
	On(event string, listener event.Listener)
	// Send 发送消息
	Send(ctx context.Context, ev *event.SseSendEvent) error
}

type client struct {
	opts Options

	listeners sync.Map
}

// NewClient 构造会话客户端
func NewClient(opts ...Option) Client {
	options := DefaultOptions()
	for _, f := range opts {
		f(&options)
	}
	fmt.Printf("Options:%+v\n", options)
	return &client{
		opts:      options,
		listeners: sync.Map{},
	}
}

// On 注册事件监听器
func (c *client) On(event string, listener event.Listener) {
	c.listeners.Store(event, listener)
}

// Send 发送消息
func (c *client) Send(ctx context.Context, ev *event.SseSendEvent) error {
	sseCli := sse.NewClient(c.opts.ConnEndpoint, func(c *sse.Client) {
		body, _ := json.Marshal(ev)
		c.Body = bytes.NewReader(body)
		c.Method = http.MethodPost
		c.Headers["Content-Type"] = "application/json"
	})

	return sseCli.SubscribeRawWithContext(ctx, func(msg *sse.Event) {
		ev := event.EventWrapper{}
		_ = json.Unmarshal(msg.Data, &ev)
		if h, ok := c.listeners.Load(string(msg.Event)); ok {
			h.(event.Listener)(ev)
		}
	})
}
